import {parse, stringify} from "qs";
import {forEach, forIn, indexOf, isArray, isEmpty, omit, trim, } from "lodash-es";
import {getRandomKey} from "../utils";
export {default as StockDirection} from './StockDirection';

// @ts-ignore
export function getPlainNode(nodeList, parentPath = '') {
    const arr: any[] = [];
    nodeList.forEach((node: any) => {
        const item = node;
        item.path = `${parentPath}/${item.path || ''}`.replace(/\/+/g, '/');
        item.exact = true;
        if (item.children && !item.component) {
            arr.push(...getPlainNode(item.children, item.path));
        } else {
            if (item.children && item.component) {
                item.exact = false;
            }
            arr.push(item);
        }
    });
    return arr;
}


function getRelation(str1: string, str2: string) {
    if (str1 === str2) {
        console.warn('Two path are equal!'); // eslint-disable-line
    }
    const arr1 = str1.split('/');
    const arr2 = str2.split('/');
    if (arr2.every((item, index) => item === arr1[index])) {
        return 1;
    }
    if (arr1.every((item, index) => item === arr2[index])) {
        return 2;
    }
    return 3;
}

function getRenderArr(routes: any[] | string[]) {
    let renderArr = [];
    renderArr.push(routes[0]);
    for (let i = 1; i < routes.length; i += 1) {
        // 去重
        renderArr = renderArr.filter(item => getRelation(item, routes[i]) !== 1);
        // 是否包含
        const isAdd = renderArr.every(item => getRelation(item, routes[i]) === 3);
        if (isAdd) {
            renderArr.push(routes[i]);
        }
    }
    return renderArr;
}

// 给官方演示站点用，用于关闭真实开发环境不需要使用的特性
export function isAntdPro() {
    return window.location.hostname === 'preview.pro.ant.design';
}

export const importCDN = (url: string, name: string | number) =>
    new Promise(resolve => {
        const dom = document.createElement('script');
        dom.src = url;
        dom.type = 'text/javascript';
        dom.onload = () => {
            // @ts-ignore
            resolve(window[name]);
        };
        document.head.appendChild(dom);
    });

export const sleepFunc = (millisecond: number | undefined, params?: any) => {
    // console.log(millisecond, params);
    return new Promise(function (resolve, reject) {
        window.setTimeout(function () {
            resolve(params);
        }, millisecond);
    }).catch((e) => {
        console.error('sleepFunc', e);
    });
};

const srcKV: any = {};

export function loadLinks(urls: [string], options: any = {}) {

    if (isEmpty(urls)) return;
    let opt: any = {rel: 'stylesheet', type: 'text/css', ...omit(options, 'v')};
    let version = options.v || '';

    forEach(urls, (url) => {
        let lkDom = document.getElementById(srcKV[`${url}`]);
        if (srcKV[`${url}`] && lkDom) {
        } else {
            let lk = document.createElement('link');
            lk.id = getRandomKey();
            lk.href = `${url}?v=${version}`;
            srcKV[`${url}`] = lk.id;
            forIn(opt, (v, k) => {
                // @ts-ignore
                lk[k] = v;
            });
            document.body.prepend(lk);
        }

    });
}


export function loadScript(url: string | undefined, callback: Function, bakURLs = [], options: any = {}) {

    if (srcKV[`${url}`] && document.getElementById(srcKV[`${url}`])) {
        callback && callback();
        return;
    }
    let opt: any = omit(options, 'v');
    let version = options.v || '';

    let script: any = document.createElement('script');
    script.type = 'text/javascript';
    // @ts-ignore
    script.async = 'async';
    script.src =`${url}${(url && url.indexOf('?') > -1)?'&':'?'}v=${version}`;
    script.id = getRandomKey();

    srcKV[`${url}`] = script.id;

    forIn(opt, (v, k) => {
        // @ts-ignore
        script[k] = v;
    });

    document.body.appendChild(script);
    if (script.readyState) {   //IE
        script.onreadystatechange = function () {
            console.log('script.readyState', script.readyState);
            if (script.readyState == 'complete' || script.readyState == 'loaded') {
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {    //非IE
        script.onload = function () {
            callback();
        };
        script.onerror = function (e: any) {
            console.log('>>> error', e);
            if (isArray(bakURLs) && !isEmpty(bakURLs)) {
                // 备用的链接
                let bakUrl = bakURLs.shift();
                loadScript(bakUrl, callback, bakURLs);
            } else {
                callback({isError: true});
            }
        };
    }
}

export function jsGetDPI() {
    var arrDPI = new Array();
    // @ts-ignore
    if (window.screen.deviceXDPI != undefined) {
        // @ts-ignore
        arrDPI[0] = window.screen.deviceXDPI;
        // @ts-ignore
        arrDPI[1] = window.screen.deviceYDPI;
    } else {
        var tmpNode = document.createElement('DIV');
        tmpNode.style.cssText = 'width:1in;height:1in;position:absolute;left:0px;top:0px;z-index:99;visibility:hidden';
        document.body.appendChild(tmpNode);
        arrDPI[0] = parseInt(String(tmpNode.offsetWidth));
        arrDPI[1] = parseInt(String(tmpNode.offsetHeight));
        // @ts-ignore
        tmpNode.parentNode.removeChild(tmpNode);
    }
    return arrDPI;
}

// 每英寸有多少像素
let dpiArr: any[];

/**
 * 毫米(mm)转为像素(px)
 * @param mm {number}
 * @param type {'x' | 'y'}
 * @return {number}
 */
export function mm2px(mm: number, type = 'x') {
    if (isEmpty(dpiArr)) {
        dpiArr = jsGetDPI() || [0, 0]; // 每英寸有多少像素
    }
    let dpiX = dpiArr[0];
    let dpiY = dpiArr[1];

    let dpiV = dpiX;
    if ('y' === type) {
        dpiV = dpiY;
    }
    return Math.floor(dpiV * mm / 25.4);
}

/**
 * 像素(px)转毫米(mm)
 * @param px {number}
 * @param type {'x' | 'y'}
 * @return {number}
 */
export function px2mm(px: number, type = 'x') {
    if (isEmpty(dpiArr)) {
        dpiArr = jsGetDPI() || [0, 0]; // 每英寸有多少像素
    }
    let dpiX = dpiArr[0];
    let dpiY = dpiArr[1];

    let dpiV = dpiX;
    if ('y' === type) {
        dpiV = dpiY;
    }
    if (dpiV != 0) {
        return Math.floor(px * 25.4 / dpiV);
    } else {
        return px;
    }
}

/**
 * Get router routing configuration
 * { path:{name,...param}}=>Array<{name,path ...param}>
 * @param {string} path
 * @param {routerData} routerData
 */
export function getRoutes(path: string, routerData: { [x: string]: any; }) {
    let routes = Object.keys(routerData).filter(
        routePath => routePath.indexOf(path) === 0 && routePath !== path,
    );
    // Replace path to '' eg. path='user' /user/name => name
    routes = routes.map(item => item.replace(path, ''));
    // Get the route to be rendered to remove the deep rendering
    const renderArr = getRenderArr(routes);
    // Conversion and stitching parameters
    const renderRoutes = renderArr.map(item => {
        const exact = !routes.some(route => route !== item && getRelation(route, item) === 1);
        return {
            exact,
            ...routerData[`${path}${item}`],
            key: `${path}${item}`,
            path: `${path}${item}`,
        };
    });
    return renderRoutes;
}

export function getPageQuery() {
    return parse(window.location.href.split('?')[1]);
}

export function getQueryPath(path = '', query = {}) {
    const search = stringify(query);
    if (search.length) {
        return `${path}?${search}`;
    }
    return path;
}

/**
 * 获取 url 上的参数
 * @param key 参数key
 * @param exceptKey
 * @param isReStr
 * @param strSearch
 */
export function getRequest(key: string, exceptKey: [], isReStr: boolean, strSearch: string) {
    var url = typeof strSearch === 'undefined' || trim(strSearch) === '' ? location.search : strSearch; //获取url中"?"符后的字串
    var theRequest = {};
    var tmpArr = [];
    var strs;
    if (url.indexOf("?") != -1) {
        if (typeof exceptKey == 'undefined' || null == exceptKey || !isArray(exceptKey)) {
            exceptKey = [];
        }
        var str = trim(url.substr(1));
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            // @ts-ignore
            if (indexOf(strs[i].split("=")[0], exceptKey) == -1) {
                tmpArr.push(strs[i]);
                // @ts-ignore
                theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
            }
        }
    }
    if (isReStr) {
        return tmpArr.join('&');
    }
    if (typeof key == 'undefined' || key == '' || !key) {
        return theRequest;
    }
    // @ts-ignore
    return theRequest[key];
}
